<?php
/**
* $Id  request.php  2006-1-9 ����05:13:29
* o2php! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
* @package		package_name package_declaration
* @copyright	Copyright (C) 2006 - 2009 Open Source Matters. All rights reserved.
* @license		GNU/GPL, see LICENSE.php
* @version $Id
*/
define('URL_STANDARD',0);
define('URL_COMPRESS',1);
define('URL_PATHINFO',2);
define('URL_MOD_REWRITE',4);
class ERequest extends EObject {
	var $url_root='/';
	var $url_script='index.php';
	var $url_q='url';
	var $url_mode=0;
	var $url_parse_mode;
	var $url_spliter='-';
	var $type='html';
	var $url;
	var $econtroller;
	var $emodel;
	var $eargs=array();
	function __construct($options) {
		$this->url_root=ERequest::getUrlRoot();
		$this->setFrom($options);
		$this->url_parse_mode=$this->url_mode;
		$this->_init();
	}
	function setParseMode($mod=URL_STANDARD){
		$this->url_parse_mode=$mod;
	}
	function _init() {
		$pathinfo = env('PATH_INFO');
		$querystring=env('QUERY_STRING');
		if($querystring && empty($pathinfo)){
			if(!empty($_GET[$this->url_q])){
				$this->url=$this->_clearUrl($_GET[$this->url_q]);
			}else{
				if(preg_match('/^[^=?&]+$/i',$querystring)){
					$this->url=$this->_clearUrl($querystring);
				}else{
					$this->url='';
				}
			}
		}elseif($pathinfo){
			$this->url=$this->_clearUrl($pathinfo);
		}else{
			$this->url='';
		}
		$this->setVar($this->get('url_q','url'),$this->url);
	}
	/**
	 * TODO
	 * $mode
	 *  0 URL_STANDARD		-/index.php?url=products-list-1.html
	 *  1 URL_COMPRESS		- /?products-list-1.html
	 *  2 URL_PATHINFO		- /index.php/products-list-1-1.html //注：iis5.0不支持，适用于服务器没开启mod_rewrite或url_rewrite的系统

	 *  4 URL_MOD_REWRITE 	- /products-list-1.html	//注：适用于服务器开通mod_rewrite或url_rewrite
	 * URL_ORIGINAL
	 * <code>
	 * $url = url('member', 'login',array(1,2),1);
	 * 返回: /index.php?url=member-login-1-2.html
	 * </code>
	 * @param string $controller
	 * @param string $model
	 * @param array $args
	 * @param int $mode
	 * @param boolean $relative
	 *
	 * @return string
	 */
	//TODO:: 将URl_STANDARD换成controller=products&model=list&category=1&page=1
	function url($controller = null, $model = null, $args = array (),$absolue = true,$mode=null,$spliter=null,$type = 'html') {
		if (empty ($controller))$controller=getCfg('defaultModule','index');
		if(empty ($model))$model=getCfg('defaultAction','index');
		if(empty($spliter))$spliter=getCfg('url_spliter','-');
		//if($mode===null)$spliter=getCfg('url_mode','0');
		$args=ERequest::_implodeArgs($args,$spliter);
		$url=$controller.$spliter.$model.$args.'.'.$type;
		if($absolue)
			$url=ERequest::addPrefix($url,$mode);
		return $url;
	}
	function _implodeArgs($args=null,$spliter='/'){
		if ($args) {
			if(is_array($args)){
				$args = $spliter.implode($spliter, $args);
			}elseif(is_string($args)){
				$args = $spliter.$args;
			}
		}else{
			$args='';
		}
		return $args;
	}
	function addPrefix($url = '', $mode = null) {
		if ($mode==null) {
			$mode = ERequest :: getUrlMode();
		}
		$request=&loadRequest();
		$root=$request->get('url_root','/');
		switch ($mode) {
			case 1 :
				$url = $root . '?' . $url;
				break;
			case 2 :
				$url = $root.$request->url_script . '/' . $url;
				break;
			case 4 :
				$url = $root.$url;//mod_rewrite
				break;
			default :
				$url = $root.$request->url_script.'?'.$request->url_q.'='.$url;
		}
		//debug($mode,$request,$root,$url);
		return $url;
	}
	function encodeUrlArgs($args) {
		$str = '';
		foreach ($args as $key => $value) {
			$str .= '&' . rawurlencode($key) . '=' . rawurlencode($value);
		}
		return substr($str, 1);
	}
	function getUrlMode() {
		static $mode;
		if (!isset ($mode)) {
			$mode = getCfg('url_mode', 0);
		}
		return $mode;
	}
	function isCgiMode() {
		return (substr(php_sapi_name(), 0, 3) == 'cgi');
	}
	function getUrlRoot() {
		static $instance;
		if (!isset ($instance)) {
			if (substr(php_sapi_name(), 0, 3) == 'cgi') {
				$script = env('SCRIPT_URL');
			} else {
				$script = env('SCRIPT_NAME');
			}
			$instance = dirname($script);
			if (strlen($instance) > 1) {
				$instance .= '/';
			} else {
				$instance = '/';
			}
		}
		return $instance;
	}
	/*
	 * 清理url中非a-zA-Z0-9及分割符的字符

	 */
	function _clearUrl($url,$spliter=null){
		if($spliter===null){
			$spliter=getCfg('url_spliter','-');
		}
		$pattern=array('/[^a-zA-Z0-9.\\'.$spliter.']/i','/(\\'.$spliter.'){2,}/');
		$replace=array('',$spliter);
		$url=preg_replace($pattern,$replace,trim($url,'.\\/-'.$spliter));
		return $url;
	}
	function parse($url, $spliter = null,$needClean=true) {
		if(empty($spliter))$spliter=$this->url_spliter;
		if($needClean)$url=$this->_clearUrl($url,$spliter);
		if (empty ($url))return false;
		$arr = array ();
		if ($pos = strrpos($url, '.')) {
			list($url_noprefix,$arr['type'])=explode('.',$url);
		} else {
			$url_noprefix = trim($url, $spliter);
			$arr['type'] = 'html';
		}
		$url_s = explode($spliter, $url_noprefix, 3);
		$ct = count($url_s);
		//debug($pos,$arr['type'],$url,$url_noprefix,$url_s,$ct);
		if ($ct === 3) {
			list ($arr['econtroller'], $arr['emodel'], $arr['eargs']) = $url_s;
			$arr['eargs'] = explode($spliter, $arr['eargs']);
		}
		elseif ($ct === 2) {
			list ($arr['econtroller'], $arr['emodel']) = $url_s;
			$arr['eargs'] = array ();
		}
		elseif ($ct === 1) {
			$arr['econtroller'] = $url_s[0];
			$arr['emodel'] = getCfg('defaultAction','index');
			$arr['eargs'] = array ();
		}
		return $arr;
	}
	function sefParse($url=null) {
		if(!empty($url)){
			$arr = $this->parse($url,null,false);
		}else{
			$arr=array(
				'econtroller'=>getCfg('defaultModule','home'),
				'emodel'=>getCfg('defaultAction','index'),
				'args'=>array(),
				'type'=>'html',
			);
			$spliter=getCfg('url_spliter','-');
			$this->url=$arr[getCfg('url_q','url')]=$arr['econtroller'].$spliter.$arr['emodel'].'.html';
		}
		foreach ($arr as $key => $value) {
			$_REQUEST[$key] = $_GET[$key] = $value;
		}
		$this->setFrom($arr);
	}
	function getVar($name, $default = null, $type = null, $hash = 'REQUEST', $mask = 0) {
		$hash = strtoupper($hash);
		if ($hash === 'METHOD') {
			$hash = strtoupper($_SERVER['REQUEST_METHOD']);
		}
		$hash = '_' . $hash;
		if (isset ($GLOBALS[$hash]) && isset ($GLOBALS[$hash][$name]) && $GLOBALS[$hash][$name] !== null) {
			$var = $GLOBALS[$hash][$name];
			if ($type !== null) {
				$type = strtolower($type);
				$types = array (
					'boolean',
					'bool',
					'integer',
					'int',
					'float',
					'string',
					'array',
					'object',
					'null'
				);
				if (in_array($type, $types)) {
					settype($var, $type);
				}
				return $var;
			}
			return $var;
		} else {
			return $default;
		}
	}
	function _getSelf(){
		return $this->url_root.$this->url;
	}
	function setVar($name, $value = null, $hash = 'REQUEST') {
		static $requests;
		if (!isset ($requests)) {
			$requests = array (
				'GET',
				'POST',
				'FILES',
				'COOKIE',
				'REQUEST'
			);
		}
		$hash = strtoupper($hash);
		if ($hash === 'METHOD') {
			$hash = strtoupper($_SERVER['REQUEST_METHOD']);
		}
		if (!in_array($hash, $requests)) {
			return $value;
		}
		$hash = '_' . $hash;
		$GLOBALS[$hash][$name] = $value;
		if ($hash === '_REQUEST') {
			$_REQUEST[$name] = $value;
			$_GET[$name] = $value;
			$_POST[$name] = $value;
		} else {
			$_REQUEST[$name] = $value;
		}
		return $value;
	}
}
?>
